package org.mule.transport.ftpext;

import java.io.IOException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.mule.api.endpoint.EndpointURI;
import org.mule.transport.ftp.FtpConnectionFactory;

/**
 *
 * @author florin
 */
public class FtpExtConnectionFactory extends FtpConnectionFactory {

    EndpointURI myUri;

    public FtpExtConnectionFactory(EndpointURI uri) {
        super(uri);
        myUri = uri;

    }

    @Override
    public Object makeObject() throws Exception {
        FTPClient client = new FTPClient();
        return client;
    }

    @Override
    public void activateObject(Object obj) throws Exception {
        FTPClient client = (FTPClient) obj;
        if (myUri.getPort() > 0) {
            client.connect(myUri.getHost(), myUri.getPort());
        } else {
            client.connect(myUri.getHost());
        }
        if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
            throw new IOException("Ftp connect failed: " + client.getReplyCode());
        }
        if (!client.login(myUri.getUser(), myUri.getPassword())) {
            throw new IOException("Ftp login failed: " + client.getReplyCode());
        }
        if (!client.setFileType(FTP.BINARY_FILE_TYPE)) {
            throw new IOException("Ftp error. Couldn't set BINARY transfer type: " + client.getReplyCode());
        }
    }

    @Override
    public void passivateObject(Object obj) throws Exception {
        FTPClient client = (FTPClient) obj;
        client.logout();
        client.disconnect();
    }
}
